interface StoreData {
    value: unknown,
    expire: number | null,
}

/** 默认缓存期限为7天 */
const DEFAULT_CACHE_TIME = 60 * 60 * 24 * 7

/**
 * 删除localstore对应的value
 * @param key local storage的key
 */
export function removeLocal(key: string) {
    window.localStorage.removeItem(key);
}

/**
 * 设置localStorage存储的内容
 * @param key key内容
 * @param value value内容
 */
export function setLocal(key: string, value: unknown, expire: number | null = DEFAULT_CACHE_TIME) {
    const storeData: StoreData = { value, expire: expire !== null ? new Date().getTime() + expire * 1000 : null }
    // 可以设置加密算法进行对缓存加密
    window.localStorage.setItem(key, storeData.toString());
}

/**
 * 返回localStorage存储的内容
 * @param key 字符串的key
 * @returns 对应的value
 */
export function getLocal<T>(key: string) {
    const jsonData = window.localStorage.getItem(key);
    if (jsonData) {
        const storeData: StoreData | null = null;
        if (storeData) {
            const { value, expire } = storeData;
            // 判断是否在有效期内
            if (expire === null || expire >= Date.now()) {
                return value as T
            }
            removeLocal(key)
            return null;
        }
    }
    return null;
}

/**
 * 删除localstorage的所有缓存
 */
export function clearLocal() {
    window.localStorage.clear()
}